import CSV from '@/components/csv';
import FileSaver from 'file-saver'
import { useIntl, FormattedMessage } from 'umi';
import {generateForm, castType} from '@/pages/generateForm'


export default class csvSaver {
    constructor(columns) {
        this.intl = useIntl()
        this.columns = columns
    }

    IntlText(e) {
        return this.intl.formatMessage({
            id: e.props.id,
        })
    }

    filterColumn(arrOfObject) {
        let ret = []
        for (let obj of arrOfObject) {
            let new_obj = Object.assign({}, obj)
            for (let key in new_obj) {
                let found = false;
                for (let col of this.columns) {
                    if (col.dataIndex == key && !(col.ignore === true)) {
                        found = true
                        break
                    }
                }
                if (!found) {
                    delete new_obj[key]
                }
            }
            ret.push(new_obj)
        }
        return ret
    }

    fieldIndexToName(arrOfObject) {
        return arrOfObject.map(row => Object.keys(row).reduce((obj, key) => {
            const col = this.columns.find(col => col.dataIndex == key)
            if (col) {
                const fieldName = this.IntlText(col.title)
                let value = row[key]
                if (col.valueEnum) {
                    for (let Enum in col.valueEnum) {
                        if (Enum == value) {
                            value = this.IntlText(col.valueEnum[Enum].text)
                            break
                        }
                    }
                }
                obj[fieldName] = value
            }
            return obj
        }, {}))
    }

    handleDataExport(selectedRows, fn = `${+new Date()}`) {
        // we need BOM prefix, sb ms.
        const result = '\uFEFF' + CSV.serializeRows(selectedRows)
        const blob = new Blob([result], {
            // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’, // xlsx
            type: 'application/vnd.ms-excel;charset=utf-8',
        });
        FileSaver.saveAs(blob, `${fn}.csv`);
    }

    exportToFile(listOfSameObj, fn = `${+new Date()}`) {
        this.handleDataExport(this.fieldIndexToName(this.filterColumn(listOfSameObj)), fn)
    }

    exportToFileEmpty(fn = `${+new Date()}`) {
        this.exportToFile([this.columns.reduce((obj, col) => {
            obj[col.dataIndex] = null
            return obj
        }, {})], fn)
    }

    fieldNameToIndex(arrOfObject) {
        console.log(arrOfObject)
        return arrOfObject.map(row => Object.keys(row).reduce((obj, key) => {
            const col = this.columns.find(col => this.IntlText(col.title) == key)
            if (col) {
                const fieldName = col.dataIndex
                let value = row[key]
                if (col.valueEnum) {
                    for (let Enum in col.valueEnum) {
                        if (this.IntlText(col.valueEnum[Enum].text) == value) {
                            value = Enum
                            break
                        }
                    }
                }
                obj[fieldName] = value
            }
            return obj
        }, {}))
    }

    async loadFromFile(file) {
        try {
            let data = await new Promise((resolve, reject) => {
                let reader = new FileReader()
                reader.onload = () => resolve(reader.result)
                reader.reject = reject
                reader.readAsText(file)
            })
            console.log(data)
            data = CSV.deserializeRows(data)
            console.log(data)
            return this.fieldNameToIndex(data)
        } catch (error) {
            console.log(error)
            return;
        }
    }

    checkColums(arrOfObj) {
        for (let col of this.columns) {
            if (col.ignore === true) {
                continue
            }
            for (let obj of arrOfObj) {
                console.log(col, obj)
                if (!obj.hasOwnProperty(col.dataIndex)) {
                    console.log(obj)
                    console.log(`don't have ${col.dataIndex}`)
                    return false
                }
                obj[col.dataIndex] = castType(col.castType, obj[col.dataIndex])
            }
        }
        return true
    }
}